package com.hotpot.comm.oss.aliyun;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.PutObjectRequest;
import com.xiaoleilu.hutool.crypto.SecureUtil;

/**
 * 描述:阿里云oss储存工具类
 * 文档:https://help.aliyun.com/document_detail/32013.html?spm=5176.doc32009.6.663.zKJK2Y
 * @author myx
 * @date 2017年7月19日 下午3:04:10
 */
public class ALiOSSUtil {
	private static Logger logger = LoggerFactory.getLogger(ALiOSSUtil.class);
	 /**
     * 访问域名
     */
    private static String endpoint = "http://oss-cn-beijing.aliyuncs.com";
    /**
     * accessKeyId
     */
    private static String accessKeyId = "LTAIkwJ5XsbXlFWa";
    /**
     * accessKeySecret
     */
    private static String accessKeySecret = "Kgb4AymS6HWYmzNOQh0dVEROP9C2CQ";
    
    /**
     * 方法描述：上传对象信息
     * @param bucketName
     * @param path
     * @return
     * @return: String
     */
    public static String uploadObject(String bucketName,String path,File file){
    	OSSClient ossClient = getOSSClient();
    	if(!ossClient.doesBucketExist(bucketName)){
    		return null;
    	}
    	String key=path+"/"+createKey();
    	ossClient.putObject(new PutObjectRequest(bucketName,key,file));
		return key;
    }
    
    
    
    
    public static void main(String[] args) throws IOException {
		ALiOSSUtil.uploadObject("muyuxitest", "file", createSampleFile());
	}
    
    
/************************************************私有方法块*********************************************************/   
    /**
     * 方法描述：获取getOSSClient实例
     * @return
     * @return: OSSClient
     */
    private static OSSClient getOSSClient(){
    	logger.info("创建OSSClient");
    	return new OSSClient(endpoint, accessKeyId, accessKeySecret);
    }
    /**
     * 方法描述：获取唯一编码
     * @return
     * @return: String
     */
    private static String createKey(){
    	return SecureUtil.simpleUUID();
    }
/************************************************私有方法块*********************************************************/
    
    private static File createSampleFile() throws IOException {
        File file = File.createTempFile("oss-java-sdk-", ".txt");
        file.deleteOnExit();

        Writer writer = new OutputStreamWriter(new FileOutputStream(file));
        writer.write("abcdefghijklmnopqrstuvwxyz\n");
        writer.write("0123456789011234567890\n");
        writer.close();

        return file;
    }

}
